package com.centanet.framework.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.widget.Toast;

import com.centanet.centalib.R;
import com.centanet.framework.interfaces.IDownloadResult;
import com.centanet.framework.interfaces.IProgressResponseListener;
import com.centanet.framework.task.DownloadTask;
import com.centanet.framework.utils.ExternalCacheDirUtil;
import com.centanet.framework.utils.MD5Util;
import com.centanet.framework.utils.OkHttpUtil;
import com.centanet.framework.utils.ProgressHelper;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.OkHttpClient;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 图片下载<p>
 * 进度的监听在非UI线程；下载结果的监听在UI线程
 */
public class ImageDownloadService extends Service {

    private final static String TAG = "ImageDownloadService";

    private ExecutorService singleTaskExecutor;//每次执行一个任务线程池
    private String cacheDir;//保存路径
    private OkHttpClient okHttpClient;
    private DownloadBinder downloadBinder = new DownloadBinder();
    private int taskCount;//下载任务数量

    @Override
    public void onCreate() {
        super.onCreate();
        cacheDir = ExternalCacheDirUtil.getImageDownloadCacheDir();
        taskCount = 0;
        okHttpClient = OkHttpUtil.getOkHttpClient();
        singleTaskExecutor = Executors.newSingleThreadExecutor();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        singleTaskExecutor.shutdown();//关闭线程池
        Logger.t(TAG).d("[线程池终结]singleTaskExecutor.isTerminated : %b", singleTaskExecutor.isTerminated());
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return downloadBinder;
    }

    /**
     * 添加任务
     *
     * @param url 下载地址
     */
    private void addTask(final String url) {
        Logger.t(TAG).d("addTask");
        if (TextUtils.isEmpty(cacheDir)) {//SD卡不可用
            Toast.makeText(getApplicationContext(), getString(R.string.sd_unable), Toast.LENGTH_SHORT).show();
            stopSelf();
            return;
        }
        final File file = new File(new File(cacheDir), MD5Util.md5(url) + ".jpg");
        if (file.exists()) {//当前图片已经存在
            Toast.makeText(getApplicationContext(), getString(R.string.image_download_already), Toast.LENGTH_SHORT).show();
            stopSelf();
            return;
//            file.delete();//debug
        }
        taskCount++;
        new DownloadTask(ProgressHelper.addProgressResponseListener(okHttpClient, new IProgressResponseListener() {
            @Override
            public void onResponseProgress(long bytesRead, long contentLength, boolean done) {//非UI线程
                if (done)
                    Logger.t(TAG).d("File size : %s", Formatter.formatFileSize(ImageDownloadService.this, contentLength));
                Logger.t(TAG).d("progress read : %d - sum : %d - progrss : %d - done : %b", bytesRead, contentLength, bytesRead * 100 / contentLength, done);
            }
        }), url, file, new IDownloadResult() {
            @Override
            public void result(boolean error) {//UI线程
                int stringRes = error ? R.string.image_download_error : R.string.image_download_success;
                if (!error) {
//                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + cacheDir)));
                MediaScannerConnection.scanFile(getApplicationContext(), new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath() + "/" +MD5Util.md5(url) + ".jpg"},  null, null);
            }
                Toast.makeText(getApplicationContext(), getString(stringRes), Toast.LENGTH_SHORT).show();
                taskCount--;
                if (taskCount == 0)
                    stopSelf();
            }
        }).executeOnExecutor(singleTaskExecutor);
    }

    public class DownloadBinder extends Binder {

        public void startDownload(String url) {
            if (!TextUtils.isEmpty(url)) {
                addTask(url);
            }
        }
    }
}
